<script setup lang="ts">
import { ExamApi } from '@/apis'
import { Message } from '@arco-design/web-vue'

const emit = defineEmits<{
  (e: 'change'): void
}>()

const visible = ref(false)
const loading = ref(false)
const uploadRef = ref()
const files = ref<any>([])

// 打开新增
const open = async () => {
  loading.value = false
  visible.value = true
}

const fileName = ref('')
const handleBeforeUpload = (file) => {
  files.value.push(file)
  fileName.value = file.name
  return false
}

// 保存
const onSave = async () => {
  try {
    uploadRef.value.submit()
    const formData = new FormData()
    formData.append('file', files.value[files.value.length - 1])
    await ExamApi.upload(formData)
    Message.success('添加成功')
    emit('change')
    visible.value = false
    while (files.value.length > 0) {
      files.value.pop()
    }
    fileName.value = ''
  } catch {
    return false
  }
}

// 重置
const reset = () => {
  uploadRef.value = null
  while (files.value.length > 0) {
    files.value.pop()
  }
  fileName.value = ''
}

defineExpose({ open })
</script>

<template>
  <ProDrawer
    v-model:visible="visible"
    :loading="loading"
    title="上传文件"
    @before-ok="onSave"
    @close="reset"
  >
    <a-card title="文件上传" class="section">
      <a-upload
        ref="uploadRef"
        accept=".xlsx"
        :auto-upload="false"
        :on-before-upload="handleBeforeUpload"
        :disabled="loading"
      >
        <template #upload-button>
          <a-space>
            <a-button>选择文件</a-button>
            <span v-if="fileName !== ''">{{ fileName }}</span>
          </a-space>
        </template>
      </a-upload>
    </a-card>
  </ProDrawer>
</template>

<style lang="less" scoped></style>
